package cn.com.bluemoon.daps.standard.service.impl;

import cn.com.bluemoon.daps.api.model.RemoteDataModelService;
import cn.com.bluemoon.daps.api.model.RemoteDataModelTableService;
import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.model.entity.DapDataModel;
import cn.com.bluemoon.daps.model.entity.DapDataModelTable;
import cn.com.bluemoon.daps.standard.client.DapSystemModuleFacade;
import cn.com.bluemoon.daps.standard.entity.DapStandardDim;
import cn.com.bluemoon.daps.standard.entity.DapStandardIndex;
import cn.com.bluemoon.daps.standard.entity.DapSystemCategory;
import cn.com.bluemoon.daps.standard.mapper.DapStandardDimMapper;
import cn.com.bluemoon.daps.standard.mapper.DapStandardIndexMapper;
import cn.com.bluemoon.daps.standard.service.DapStandardDimService;
import cn.com.bluemoon.daps.standard.service.DapSystemCategoryService;
import cn.com.bluemoon.daps.standard.vo.DimSearchVo;
import cn.com.bluemoon.daps.system.vo.BizLineResponseVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 数据标准维度 服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-09-23
 */
@Slf4j
@Service
public class DapStandardDimServiceImpl extends ServiceImpl<DapStandardDimMapper, DapStandardDim>
        implements DapStandardDimService {

    @Resource
    DapStandardDimMapper dapStandardDimMapper;

    @Resource
    DapSystemModuleFacade dapSystemModuleFacade;

    @Resource
    DapStandardIndexMapper dapStandardIndexMapper;

    @Resource
    DapSystemCategoryService dapSystemCategoryService;

    @Resource
    RemoteDataModelTableService remoteDataModelTableService;

    @Resource
    RemoteDataModelService remoteDataModelService;

    @Override
    public IPage<DapStandardDim> getDimList(DimSearchVo dimSearchVo) {

        Page<DapStandardDim> page = new Page<>(dimSearchVo.getPageNum(), dimSearchVo.getPageSize());
        IPage<DapStandardDim> dimPage = dapStandardDimMapper.selectDimList(page, dimSearchVo);
        List<DapStandardDim> dims = dimPage.getRecords();
        // 模型表id集合
        List<String> collect = dims.stream().filter(d -> StringUtils.isNotBlank(d.getModelTableId())).map(DapStandardDim::getModelTableId).collect(Collectors.toList());
        if (!collect.isEmpty()) {
            ResultBean<List<DapDataModelTable>> resultBean = remoteDataModelTableService.getTableList(collect);
            List<DapDataModelTable> tableList = resultBean.getContent();
            if (tableList != null && !tableList.isEmpty()) {
                Map<String, String> map = tableList.stream().collect(Collectors.toMap(DapDataModelTable::getId, DapDataModelTable::getEngName));
                List<DapStandardDim> dimList = dims.stream()
                        .filter(d -> map.containsKey(d.getModelTableId()))
                        .peek(d -> d.setTableName(map.get(d.getModelTableId())))
                        .collect(Collectors.toList());
                List<DapStandardDim> oldDim = dims.stream().filter(d -> collect.contains(d.getModelTableId())).collect(Collectors.toList());
                dims.removeAll(oldDim);
                dims.addAll(dimList);
            }
        }
        return dimPage;
    }

    @Override
    public ResultBean<String> addDapStandardDim(DapStandardDim dapStandardDim) {

        // 名称、简称校验
        ResultBean<String> resultBean = checkDim(dapStandardDim);
        if (resultBean.getCode() == 200) {
            return save(dapStandardDim) ? ResultBean.ok("保存成功") : ResultBean.error("保存失败");
        }
        return resultBean;

    }

    @Override
    public ResultBean<String> updateDapStandardDim(DapStandardDim dapStandardDim) {

        // id校验
        if (StringUtils.isBlank(dapStandardDim.getId())) {
            return ResultBean.error("维度id不能为空");
        }
        // 名称、简称校验
        ResultBean<String> resultBean = checkDim(dapStandardDim);
        if (resultBean.getCode() == 200) {
            return updateById(dapStandardDim) ? ResultBean.ok("更新成功") : ResultBean.error("更新失败");
        }
        return resultBean;
    }

    @Override
    @Transactional
    public ResultBean<String> deleteDapStandardDim(List<String> ids) {

        // 查询维度是否被绑定
        List<String> list = new ArrayList<>();
        for (String id : ids) {
            List<DapStandardIndex> dapStandardIndices = dapStandardIndexMapper.selectList(new LambdaQueryWrapper<DapStandardIndex>()
                    .like(DapStandardIndex::getAssociationDimension, id));
            if (!dapStandardIndices.isEmpty()) {
                list.add(id);
            }
        }
        if (!list.isEmpty()) {
            List<DapStandardDim> dapStandardDims = this.getBaseMapper().selectBatchIds(list);
            List<String> names = dapStandardDims.stream().map(DapStandardDim::getCodeName).collect(Collectors.toList());
            return ResultBean.error(String.format("维度%s被指标引用，删除失败", names));
        }
        this.getBaseMapper().deleteBatchIds(ids);
        return ResultBean.ok("删除成功");
    }

    @Override
    public ResultBean<DapStandardDim> dapStandardDimInfo(String id) {

        DapStandardDim dapStandardDim = getBaseMapper().selectById(id);
        // 业务线
        BizLineResponseVo bizLineResponseVo = dapSystemModuleFacade.getBizLineInfoById(dapStandardDim.getBizLineId());
        dapStandardDim.setBizName(bizLineResponseVo != null ? bizLineResponseVo.getCodeName() : "");
        if (StringUtils.isNotBlank(dapStandardDim.getThemeId())) { // 主题
            DapSystemCategory dapSystemCategory = dapSystemCategoryService.getBaseMapper().selectById(dapStandardDim.getThemeId());
            dapStandardDim.setThemeName(dapSystemCategory.getCodeName());
        }
        if (StringUtils.isNotBlank(dapStandardDim.getModelTableId())) { // 表
            ResultBean<List<DapDataModelTable>> result = remoteDataModelTableService.getTableList(Arrays.asList(dapStandardDim.getModelTableId()));
            List<DapDataModelTable> content = result.getContent();
            DapDataModelTable table = content.stream().findFirst().get();
            String modelId = table.getDataModelId();
            ResultBean<DapDataModel> resultBean = remoteDataModelService.getById(modelId);
            String systemId = resultBean.getContent().getSystemId();
            dapStandardDim.setModelId(modelId);
            dapStandardDim.setSystemId(systemId);
            dapStandardDim.setTableName(table.getEngName());
        }
        return ResultBean.ok(dapStandardDim);
    }


    public ResultBean<String> checkDim(DapStandardDim dapStandardDim) {

        // 名称、简称校验
        List<DapStandardDim> dapStandardDims = dapStandardDimMapper.selectList(new LambdaQueryWrapper<DapStandardDim>()
                .eq(DapStandardDim::getCodeName, dapStandardDim.getCodeName()).or().eq(DapStandardDim::getCode, dapStandardDim.getCode()));
        if (StringUtils.isNotBlank(dapStandardDim.getId())) {
            dapStandardDims = dapStandardDims.stream().filter(d -> !d.getId().equals(dapStandardDim.getId())).collect(Collectors.toList());
        }
        if (!dapStandardDims.isEmpty()) {
            return ResultBean.error("名称或简称重复!");
        }
        // 维度校验
        List<Integer> type = Arrays.asList(0, 1);
        if (!type.contains(dapStandardDim.getType())) {
            return ResultBean.error("维度类型值错误");
        }
        // 业务线正确性校验
        BizLineResponseVo line = dapSystemModuleFacade.getBizLineInfoById(dapStandardDim.getBizLineId());
        if (line == null) {
            return ResultBean.error("绑定的业务线不存在");
        }
        return ResultBean.ok("");
    }
}
